package cn.wsw.hrm.handler;

import cn.wsw.hrm.client.FastdfsClient;
import cn.wsw.hrm.config.RabbitMqConfig;
import cn.wsw.hrm.utils.RabbitmqConstant;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import feign.Response;
import org.apache.commons.io.IOUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

@Component
public class StaticPageHandler {
    @RabbitListener(queues = RabbitMqConfig.QUEUE_PAGE_STATIC)
    public void handle(String msg, Message message, Channel channel) {
        Map map = JSONObject.parseObject(msg, Map.class);
        Integer fileSysType = (Integer) map.get(RabbitmqConstant.FILE_SYS_TYPE);
        String pageUrl = (String) map.get(RabbitmqConstant.PAGE_URL);
        String physicalPath = (String) map.get(RabbitmqConstant.PHYSICAL_PATH);
        //判断是那个文件系统，分别做处理

        switch (fileSysType) {
            case 0: //fastdfs
                downloadAndCopyOfFastDfs(pageUrl, physicalPath);
                break;
            case 1: //hdfs
                downloadAndCopyOfFastDfs(pageUrl, physicalPath);
                break;

        }


        //@TODO hdfs以后支持
        private void downloadAndCopyOfHdfs(String pageUrl,String; physicalPath){
          }
    }
    @Autowired
    private FastdfsClient fastDfsClient;
    private void downloadAndCopyOfFastDfs(String pageUrl,String physicalPath) {
        InputStream is = null;
        FileOutputStream os = null;
        try {
            //以pageUrl到fastdfs下载文件
            Response response = fastDfsClient.download(pageUrl);
            is = response.body().asInputStream();
            //放入特定文件
            System.out.println(physicalPath);
            os = new FileOutputStream(physicalPath);
            IOUtils.copy(is, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {

                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
